package com.coollang.smartbra.presenter;

import com.coollang.smartbra.activity.SearchActivity;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.constant.Constants;
import com.coollang.smartbra.http.HttpCallBack;
import com.coollang.smartbra.http.MyHttp;
import com.coollang.smartbra.model.BaseModel;
import com.coollang.smartbra.model.BindDeviceModel;
import com.coollang.smartbra.model.DeviceModel;
import com.coollang.smartbra.utils.ToastUtils;
import com.google.gson.Gson;

import java.util.HashMap;

import io.realm.Realm;
import okhttp3.Call;
import okhttp3.Response;

/**
 * @author Timmy
 *         蓝牙搜索p层
 */
public class SearchActivityPresenter {
    private Realm mRealm;
    private SearchActivity mSearchActivity;
    private Gson mGson;
    public DeviceModel mDeviceModel;

    public SearchActivityPresenter(SearchActivity searchActivity) {
        mSearchActivity = searchActivity;
        mGson = new Gson();
        mRealm = Realm.getDefaultInstance();
    }

    /**
     * 检测设备是否被绑定
     */
    public void setIsBindingInfoInfo(String deviceMac) {
        HashMap<String, String> hashMap = new HashMap<>(16);
        hashMap.put(Constants.Params.MAC, deviceMac.replace(":", ""));
        hashMap.put(Constants.Params.USERNAME, MyApplication.mLogInDataBean.getUsername());

        MyHttp.getInstance().isBinding(hashMap, new HttpCallBack() {
            @Override
            public void onSuccess(String results, Call call, Response response) {
                BaseModel model = mGson.fromJson(results, BaseModel.class);
                int code = Integer.parseInt(model.getCode());
                if (code == 200) {
                    mSearchActivity.onCheckSucceed(model.getData());
                } else {
                    onError(call, response, new RuntimeException("错误"));
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                mSearchActivity.stopScan();
            }
        });
    }

    /**
     * 绑定设备
     */
    public void bindDevice(String deviceMac) {
        HashMap<String, String> hashMap = new HashMap<>(16);
        hashMap.put(Constants.Params.MAC, deviceMac.replace(":", ""));
        hashMap.put(Constants.Params.USERNAME, MyApplication.mLogInDataBean.getUsername());

        MyHttp.getInstance().bindingDevice(hashMap, new HttpCallBack() {
            @Override
            public void onSuccess(String results, Call call, Response response) {
                BindDeviceModel infoModel = mGson.fromJson(results, BindDeviceModel.class);

                if (infoModel.getCode() == 200) {
                    // 保存该数据到
                    saveDeviceList(infoModel.getData());
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                ToastUtils.showToast("服务器连接失败！");
            }
        });
    }

    /**
     * 解绑设备
     */
    public void unBindDevice(String deviceMac) {
        HashMap<String, String> hashMap = new HashMap<>(16);
        hashMap.put(Constants.Params.MAC, deviceMac.replace(":", ""));

        MyHttp.getInstance().unbindingDevice(hashMap, new HttpCallBack() {
            @Override
            public void onSuccess(String results, Call call, Response response) {
                super.onSuccess(results, call, response);
                BaseModel model = mGson.fromJson(results, BaseModel.class);
                int code = Integer.parseInt(model.getCode());

                if (code == 200) {
                    mRealm.beginTransaction();
                    mRealm.delete(DeviceModel.class);
                    mRealm.commitTransaction();
                    mSearchActivity.unBindSucceed();
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
            }
        });
    }

    /**
     * 查询绑定设备列表
     */
    public void queryDeviceList() {
        mDeviceModel = mRealm.where(DeviceModel.class).findFirst();
        if (mDeviceModel != null) {
            mSearchActivity.mDeviceListAdapter.checkMac(mDeviceModel.getDeviceMac());
        }
    }

    /**
     * 判断点击的是否是自己绑定的设备
     *
     * @param searchResult
     * @return
     */
    public boolean checkIsBind(String searchResult) {
        if (mDeviceModel == null) {
            return false;
        } else if (!searchResult.equals(mDeviceModel.getDeviceMac())) {
            return false;
        }
        return true;
    }

    /**
     * 保存到数据库中
     */
    private void saveDeviceList(final BindDeviceModel.DataBean data) {
        mRealm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                DeviceModel model = new DeviceModel();
                model.setDeviceID(data.getId());
                model.setDeviceMac(data.getMac());
                model.setDeviceName(data.getNickname());
                realm.copyToRealmOrUpdate(model);
            }
        });
    }
}
